package com.example.keymanagers;

import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.keymanagers.Dao.KeyDao;
import com.example.keymanagers.bean.Bean;
import com.example.keymanagers.keyAdapter.adapter;

import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ListView lv;
    private Adapter adapter;

    private List<Bean> list;
    private AlertDialog alertDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=findViewById(R.id.lv);
        KeyDao dao=new KeyDao(this);
        list = dao.getall();

        adapter = new adapter(list);
        lv.setAdapter((ListAdapter) adapter);
        lv.setOnItemClickListener(this);




    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if(adapterView==lv){
            if(alertDialog==null){
            alertDialog = new AlertDialog.Builder(this)
                      .setCancelable(false)
                    .setTitle("请稍后..")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            alertDialog.dismiss();
                            Toast.makeText(MainActivity.this, "开门任务被终止", Toast.LENGTH_SHORT).show();
                            handler.removeCallbacks(run);
                        }
                    }).create();
            }

            alertDialog.setMessage("正在开门"+list.get(i).getRoom());
            alertDialog.show();
       handler.postDelayed(run,2000);

        }





    }
    private Handler handler=new Handler();

    private Runnable run=new Runnable() {
        @Override
        public void run() {
            alertDialog.dismiss();
            Toast.makeText(MainActivity.this, "门打开了", Toast.LENGTH_SHORT).show();

        }
    };


    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
